package com.wyz.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import com.wyz.bean.Record;
import com.wyz.json.Jackson;

import my.util.ResponseUtils;


@MultipartConfig
@WebServlet("/api/upload")
public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// layui的文件上传字段名叫file
		Part part = req.getPart("file");
		if(part == null) return;
		
		String head = part.getHeader("content-disposition");
		String fname = head.replaceFirst(".*filename=\"(.*?)\".*", "$1");
		
		// 文件上传目录
		String dir = req.getServletContext().getRealPath("/upload");
		String ext = FilenameUtils.getExtension(fname);
		String uuid = UUID.randomUUID().toString().replace("-", "");
		
		File file = new File(dir, uuid + "." + ext);
		// 进行文件读写
		InputStream is = part.getInputStream();
		OutputStream os = new FileOutputStream(file);
		IOUtils.copy(is, os);
		is.close();
		os.close();
		
		// 返回一个JSON
		Map<String, Object> map = new HashMap<>();
		map.put("src", req.getContextPath() + "/upload/" + file.getName());
		map.put("title", fname);
		Record record = new Record(true, 0, "上传成功");
		record.setData(map);
		
		String json = Jackson.me().toJson(record);
		ResponseUtils.renderJson(resp, json);		
	}
}
